<?php
/**
 * Created by PhpStorm.
 * User: 悟能科技
 * Date: 2018/8/27
 * Time: 16:43
 */

namespace app\api\controller;


use app\api\controller\Pub;

use app\common\controller\ActionLogs;
use app\common\controller\Platurl;
use app\common\model\Agent;
use app\common\model\CardBizPut;
use app\common\model\CardMember;
use app\common\model\CardQrcode;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\WxOpen;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Cardusextend extends Pub
{

    //开卡组件二维码
//    public function cardusbizqrcode(Request $request){
//        $param = $request->param();
//        $CardQrcode = new CardQrcode();
//        $map['c_id'] = $param['c_id'];
//        $list = $CardQrcode->where($map)->paginate(20);
//        $card['c_id'] = $param['c_id'];
//        $this->assign('card', $card);
//        $this->assign('list', $list);
//        return $this->fetch();
//    }

    //开卡
    public function cardusbizadd($param){
        $CardMember = new CardMember();
        $cardinfo = $CardMember->where(['id' => $param['c_id']])->field('top_mid,card_id,mid,id')->find();
//        $ActionLogs = new ActionLogs();
//        $ActionLogs->writelog("osapi", "clientlog", "cardusbizadd", "1:", $cardinfo);
        $data['card_id'] = $cardinfo['card_id'];
        $data['outer_str'] = $param['outer_str'];
//        $ActionLogs->writelog("osapi", "clientlog", "cardusbizadd", "2:", $data);
        $options = $this->options($cardinfo['card_id']);
        $weObj = new Wxobjopen($options);
        $access_token = $weObj->get_authorizer_access_token();
        $urls = 'https://api.weixin.qq.com/card/membercard/activate/geturl?access_token='.$access_token;
        $ress = $this->http_post($urls,json_encode($data,JSON_UNESCAPED_UNICODE));
//        $ActionLogs->writelog("osapi", "clientlog", "cardusbizadd", "3:", $ress);
//        return $data;
        $res = json_decode($ress,true);
        if ($res['errcode'] == 0){
            //存储数据
            $CardQrcode = new CardQrcode();
            $dates['top_mid'] = $cardinfo['top_mid'];
            $dates['mid'] = $param['outer_str'];
            $dates['c_id'] = $cardinfo['id'];
            $dates['card_id'] = $cardinfo['card_id'];
            $dates['url'] = $res['url'];
            $dates['type'] = 1;
            $dates['outer_str'] = $param['outer_str'];
            $dates['create_time'] = time();
            $CardQrcode->allowField(true)->save($dates);
//            $ActionLogs->writelog("osapi", "clientlog", "cardusbizadd", "4:", $dates);
            //END
            $id = $CardQrcode->id;
            $Platurl = new Platurl();
            $url['platurl'] = $Platurl->getagenturl('top_mid', $cardinfo['top_mid']);
            $dataa['url_mobile'] = $url['platurl'].'/mobile.php?s=/cardopen/index/type/BIZ/qrcode/'.$id;
//            $dataa['qrcode_url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/bizcard/'.$id.'.png';
            $CardQrcode->save($dataa,['id'=>$id]);
//            $ActionLogs->writelog("osapi", "clientlog", "cardusbizadd", "5:", $dataa);
//            $this->scbizqrcode($id);
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '成功';
            $rarr['data'] = $res['url'];
            $rarr['result_code'] = 'SUCCESS';
            $rarr['result_msg'] = '成功';
        }else{
            $rarr['return_code'] = "SUCCESS";
            $rarr['return_msg'] = '失败';
            $rarr['data'] = '';
            $rarr['result_code'] = 'FAIL';
            $rarr['result_msg'] = $res['errmsg'];
        }
//        $ActionLogs->writelog("osapi", "clientlog", "cardusbizadd", "6:", $rarr);
        return $rarr;
    }

    //开卡
//    public function cardusbizcreate(Request $request){
//        if ($request->isAjax()) {
//            $param = $request->param();
//            $CardMember = new CardMember();
//            $cardinfo = $CardMember->where(['id' => $param['c_id']])->find('top_mid,card_id,mid,id')->find();
//            $data['card_id'] = $cardinfo['card_id'];
//            $data['outer_str'] = $param['outer_str'];
//            $options = $this->options($cardinfo['card_id']);
//            $weObj = new Wxobjopen($options);
//            $access_token = $weObj->get_authorizer_access_token();
//            $url = 'https://api.weixin.qq.com/card/membercard/activate/geturl?access_token='.$access_token;
//            $ress = $this->http_post($url,$data);
//            $res = json_decode($ress,true);
//            if ($res['errcode'] == 0){
//                //存储数据
//                $CardQrcode = new CardQrcode();
//                $dates['top_mid'] = $cardinfo['top_mid'];
//                $dates['mid'] = $cardinfo['mid'];
//                $dates['c_id'] = $cardinfo['c_id'];
//                $dates['card_id'] = $cardinfo['card_id'];
//                $dates['url'] = $res['url'];
//                $dates['outer_str'] = $param['outer_str'];
//                $dates['create_time'] = time();
//                $CardQrcode->allowField(true)->save($dates);
//                $rarr['return_code'] = "SUCCESS";
//                $rarr['return_msg'] = '成功';
//                $rarr['data'] = $res['url'];
//                $rarr['result_code'] = 'SUCCESS';
//                $rarr['result_msg'] = '成功';
//            }else{
//                $rarr['return_code'] = "SUCCESS";
//                $rarr['return_msg'] = '失败';
//                $rarr['data'] = '';
//                $rarr['result_code'] = 'FAIL';
//                $rarr['result_msg'] = $res['errmsg'];
//            }
//            return json($rarr);
//        }else{
//
//            return $this->fetch();
//        }
//    }

    public function scbizqrcode($id)
    {
        try {
            $CardQrcode = new CardQrcode();
            $cqrcode = $CardQrcode->where(['id' => $id])->field('url,url_mobile')->find();
//            $ActionLogs = new ActionLogs();
//            $ActionLogs->writelog("osapi", "clientlog", "cardusbizadd", "r:", $cqrcode);
            action('Qrcodes/cardbizqrcode', array($id, $cqrcode['url_mobile'] . ".html"));
        }catch (\Exception $e) {
            $data['return_msg'] = $e->getMessage();
        }
    }
//
//
//    public function getbizqrcode(Request $request)
//    {
//        $param = $request->param();
//        $CardQrcode = new CardQrcode();
//        $cqrcode = $CardQrcode->where(['id'=>$param['id']])->field('url,url_mobile')->find();
//        $jg = action('Qrcodes/cardbizqrcode', array($param['id'],$cqrcode['url_mobile'] . ".html"));
//        $qr = $jg;
//        $length = filesize($qr);
//        $type = mime_content_type($qr);
//        $showname = ltrim(strrchr($qr, '/'), '/');
//        header("Content-Description: File Transfer");
//        header('Content-type: ' . $type);
//        header('Content-Length:' . $length);
//        if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
//            header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
//        } else {
//            header('Content-Disposition: attachment; filename="' . $showname . '"');
//        }
//        readfile($qr);
//        exit;
//    }
//
//    public function getgivecardid($arr)
//    {
//        $arr = json_decode($arr, JSON_UNESCAPED_UNICODE);
//        if ($arr) {
//            $CardGeneral = new \app\common\model\CardGeneral();
//            foreach ($arr as $k => $v) {
//                $datas[$k] = $CardGeneral->where(['id' => $v['zs_c_id']])->value('title') . '[' . $v['zs_no'] . '张' . ']';
//            }
//            if ($datas) {
//                $data = implode(',', $datas);
//            } else {
//                $data = '';
//            }
//        } else {
//            $data = '';
//        }
//        return $data;
//    }
//
//
//
//    //获取跟随推荐信息
//    public function getbonusbizput($param){
//        $CardBizPut = new CardBizPut();
//        $Merchant = new Merchant();
//        $mach = $Merchant->where(['id'=>$param['merchantid']])->field('top_mid,agent')->find();
//        $top_mid = $mach['top_mid'];
//        $info = $CardBizPut->where(['top_mid'=>$top_mid])->find();
//        if ($info){
//            $rarr['code'] = 0;
//            $rarr['data']['card'] = $this->getgivecardid($info['c_id_list']);
//            $rarr['data']['end_time'] = date("Y-m-d h:i:s",$info['end_time']);
//            $rarr['message'] = 'SUCCESS';
//        }else{
//            $rarr['code'] = 9001;
//            $rarr['data'] = '';
//            $rarr['message'] = 'ERROR';
//        }
//        return json($rarr);
//
//    }
    

    //微信API参数  根据card_id获取
    public function options($card_id)
    {
        $CardMember = new CardMember();
        $Merchant = new Merchant();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $map['id'] = $CardMember->where('card_id', $card_id)->value('mid');
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }


    public function http_post($url, $param, $post_file = false)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
            $is_curlFile = true;
        } else {
            $is_curlFile = false;
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        if (is_string($param)) {
            $strPOST = $param;
        } elseif ($post_file) {
            if ($is_curlFile) {
                foreach ($param as $key => $val) {

                    if (substr($val, 0, 1) == '@') {

                        $param[$key] = new \CURLFile(realpath(substr($val, 1)));
                    }
                }
            }
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    public function http_get($url)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }
}